from starlette.types import ASGIApp, Receive, Scope, Send
from starlette.requests import Request

import logging


from ..server.service.local._UserHistoryCacheService import _ChatHistoryCacheService
from ..init.Global import user2chat_history, configuration, chatHistoryMap


class ChatHistoryMiddleware:

    def __init__(self, app: ASGIApp):
        self.app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send):
        if scope["type"] == "http":
            await self.call(scope, receive, send)
            return
        await self.app(scope, receive, send)

    async def call(self, scope: Scope, receive: Receive, send: Send):
        request = Request(scope)
        if request in chatHistoryMap:
            logging.info(f"拦截到请求: {str(request.url)}")
            await self.before_history(request)
            await self.app(scope, receive, send)
            await self.after_history(request)
            return
        await self.app(scope, receive, send)

    async def before_history(self, request: Request):
        sessionId = request.headers.get("sessionId", None)
        if sessionId is None:
            return
        sessionId = int(sessionId)
        token = user2chat_history.set(
            await _ChatHistoryCacheService.get_history(
                sessionId, configuration.cache.max_use_history, configuration.redis.time
            )
        )

    async def after_history(self, request: Request):
        sessionId = request.headers.get("sessionId", None)
        if sessionId is None:
            return
        sessionId = int(sessionId)
        await _ChatHistoryCacheService.add_history(
            sessionId,
            user2chat_history.get()[-2:],
            configuration.redis.time,
        )
